/*
 * Created by JFormDesigner on Tue Dec 24 14:08:22 ICT 2013
 */

package fashionshop.gui;

import java.awt.*;
import java.awt.event.*;
import java.math.BigDecimal;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

import fashionshop.bll.CategoryBLL;
import fashionshop.bll.OrderBLL;
import fashionshop.bll.OrderDetailBLL;
import fashionshop.bll.ProductBLL;

/**
 * @author Hoan Tran
 */
public class ProductAdd extends JDialog {
	
	private int currentOrder;
	private boolean canEdit;
	private String orderSum = "0";
	public boolean isCanEdit() {
		return canEdit;
	}

	public void setCanEdit(boolean canEdit) {
		this.canEdit = canEdit;
	}

	public int getCurrentOrder() {
		return currentOrder;
	}

	public void setCurrentOrder(int currentOrder) {
		this.currentOrder = currentOrder;
	}
	
	public String getOrderSum() {
		return orderSum;
	}

	public void setOrderSum(String orderSum) {
		this.orderSum = orderSum;
	}

	private Vector productAddTableRecords;
	private Vector productAddTableTitle;
	private Vector orderDetailTableRecords;
	private Vector orderDetailTableTitle;
	
	private void LoadOrderDetail() throws Exception{
		orderDetailTableTitle = new Vector();
		orderDetailTableRecords = new Vector();
		tableOrderDetail.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableOrderDetail.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "none");
		tableOrderDetail.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "none");
		orderDetailTableTitle.add("ID Đơn hàng");
		orderDetailTableTitle.add("ID Sản phẩm");
		orderDetailTableTitle.add("Mã Sản phẩm");
		orderDetailTableTitle.add("Tên Sản phẩm");
		orderDetailTableTitle.add("Số lượng");
		orderDetailTableTitle.add("Đơn giá");
		orderDetailTableTitle.add("Tổng cộng");
		OrderDetailBLL orderDetailBll = new OrderDetailBLL();
		orderDetailTableRecords = orderDetailBll.loadOrderDetail(currentOrder);
		tableOrderDetail.setModel(new DefaultTableModel(orderDetailTableRecords, orderDetailTableTitle));
		
	}
	
	private void LoadProduct() throws Exception{
		productAddTableTitle = new Vector();
		productAddTableRecords = new Vector();
		tableProductAdd.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tableProductAdd.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "none");
		tableProductAdd.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "none");
		productAddTableTitle.add("ID");
		productAddTableTitle.add("Phân loại");
		productAddTableTitle.add("Tên sản phẩm");
		productAddTableTitle.add("Mã sản phẩm");
		productAddTableTitle.add("Số lượng");
		productAddTableTitle.add("Hình ảnh");
		productAddTableTitle.add("Màu sắc");
		productAddTableTitle.add("Giá");
		productAddTableTitle.add("Mô tả");
		productAddTableTitle.add("Ngày tạo");
		productAddTableTitle.add("Giá khuyến mãi");
		ProductBLL productBll = new ProductBLL();
		productAddTableRecords = productBll.loadAllProduct();
		tableProductAdd.setModel(new DefaultTableModel(productAddTableRecords, productAddTableTitle));
		
	}
	
	public ProductAdd(Frame owner) {
		super(owner);
		initComponents();
	}

	public ProductAdd(Dialog owner) {
		super(owner);
		initComponents();
	}

	private void txtProductAddQuantityKeyTyped(KeyEvent e) {
		// TODO add your code here
		char vChar = e.getKeyChar();
        if (!(Character.isDigit(vChar)
                || (vChar == KeyEvent.VK_BACK_SPACE)
                || (vChar == KeyEvent.VK_DELETE))) {
            e.consume();
        }
	}

	private void btnProductAddSearchActionPerformed(ActionEvent e)  {
		// TODO add your code here
		String keyword;
		keyword = txtProductAddKeyword.getText();
		ProductBLL productBll = new ProductBLL();
		try {
			productAddTableRecords = productBll.BasicSearch(keyword);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		tableProductAdd.setModel(new DefaultTableModel(productAddTableRecords, productAddTableTitle));
	}

	private void btnProductAddActionPerformed(ActionEvent e) {
		// TODO add your code here
		int selectedRow = tableProductAdd.getSelectedRow();
		if(txtProductAddQuantity.getText() == null || txtProductAddQuantity.getText().isEmpty() || txtProductAddQuantity.getText().equals("")){
			JOptionPane.showMessageDialog(this, "Chưa nhập số lượng sản phẩm", "Lỗi", JOptionPane.ERROR_MESSAGE);
			return;
		}
        if (selectedRow != -1) {
			Vector selectedProduct = (Vector) productAddTableRecords.get(selectedRow);
	        boolean flag = true;
	        int selectedID = Integer.parseInt(selectedProduct.get(0).toString());
	        for(int i = 0; i < tableOrderDetail.getRowCount(); i++){
	        	int orderDetailProductID = Integer.parseInt(tableOrderDetail.getValueAt(i, 1).toString());
	        	if(selectedID == orderDetailProductID){
	        		int quantity = Integer.parseInt(txtProductAddQuantity.getText().toString()) + Integer.parseInt(tableOrderDetail.getValueAt(i, 4).toString());
	        		tableOrderDetail.setValueAt(quantity, i, 4);
	        		
	        		if(selectedProduct.get(10).toString().equals("0")){
			        	BigDecimal price = new BigDecimal(selectedProduct.get(7).toString());
			        	tableOrderDetail.setValueAt(price, i, 5);
			        	BigDecimal sum = price.multiply(BigDecimal.valueOf(quantity));
			        	
			        	tableOrderDetail.setValueAt(sum, i, 6);
			        }
			        else{
			        	BigDecimal price = new BigDecimal(selectedProduct.get(10).toString());
			        	tableOrderDetail.setValueAt(price, i, 5);
			        	BigDecimal sum = price.multiply(BigDecimal.valueOf(quantity));
			        	
			        	tableOrderDetail.setValueAt(sum, i, 6);
			        }
	        		flag = false;
	        		break;
	        	}
	        }
	        if(flag){
	        	Vector record = new Vector();
	        	record.add(currentOrder);
				record.add(selectedProduct.get(0).toString());
		        record.add(selectedProduct.get(3).toString());
		        record.add(selectedProduct.get(2).toString());
		        record.add(txtProductAddQuantity.getText());
		        if(selectedProduct.get(10).toString().equals("0")){
		        	BigDecimal price = new BigDecimal(selectedProduct.get(7).toString());
		        	record.add(price);
		        	record.add(price.multiply(new BigDecimal(txtProductAddQuantity.getText())));
		        }
		        else{
		        	BigDecimal price = new BigDecimal(selectedProduct.get(10).toString());
		        	record.add(price);
		        	record.add(price.multiply(new BigDecimal(txtProductAddQuantity.getText())));
		        }
	        	orderDetailTableRecords.add(record);
	        	tableOrderDetail.setModel(new DefaultTableModel(orderDetailTableRecords, orderDetailTableTitle));
	        }
	        
	        
        }
        else{
        	JOptionPane.showMessageDialog(this, "Chưa chọn sản phẩm", "Lỗi", JOptionPane.ERROR_MESSAGE);
        }
	}

	private void thisWindowOpened(WindowEvent e) {
		// TODO add your code here
		try {
			this.LoadProduct();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			this.LoadOrderDetail();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		btnProductDelete.setEnabled(canEdit);
		txtProductAddQuantity.setEnabled(canEdit);
		btnProductAdd.setEnabled(canEdit);
	}

	private void btnProductDeleteActionPerformed(ActionEvent e) {
		// TODO add your code here
		int selectedRow = tableOrderDetail.getSelectedRow();
        if (selectedRow != -1) {
        	orderDetailTableRecords.remove(selectedRow);
			tableOrderDetail.setModel(new DefaultTableModel(orderDetailTableRecords, orderDetailTableTitle));
        }
	}

	private void btnOrderDetailReloadActionPerformed(ActionEvent e) {
		// TODO add your code here
		try {
			this.LoadOrderDetail();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	private void btnOrderDetailSaveAllActionPerformed(ActionEvent e) {
		// TODO add your code here
		OrderDetailBLL orderDetailBll = new OrderDetailBLL();
		try {
			if(orderDetailBll.SaveAll(currentOrder, orderDetailTableRecords))
				JOptionPane.showMessageDialog(this, "Lưu dữ liệu thành công", "Thông báo", JOptionPane.INFORMATION_MESSAGE);
			else
				JOptionPane.showMessageDialog(this, "Lưu dữ liệu thất bại", "Lỗi", JOptionPane.ERROR_MESSAGE);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		try {
			this.LoadOrderDetail();
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		BigDecimal sum = BigDecimal.ZERO;
		for(int i = 0; i < tableOrderDetail.getRowCount(); i++){
			sum = sum.add(new BigDecimal(tableOrderDetail.getValueAt(i, 6).toString()));
		}
		this.setOrderSum(sum.toString());
//		this.dispose();
	}

	private void btnOrderReloadActionPerformed(ActionEvent e) {
		// TODO add your code here
	}

	private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		// Generated using JFormDesigner Evaluation license - Hoan Tran
		scrollPane1 = new JScrollPane();
		tableProductAdd = new JTable();
		btnProductAdd = new JButton();
		txtProductAddQuantity = new JTextField();
		label1 = new JLabel();
		txtProductAddKeyword = new JTextField();
		label2 = new JLabel();
		btnProductAddSearch = new JButton();
		scrollPane2 = new JScrollPane();
		tableOrderDetail = new JTable();
		btnProductDelete = new JButton();
		btnOrderDetailReload = new JButton();
		btnOrderDetailSaveAll = new JButton();

		//======== this ========
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowOpened(WindowEvent e) {
				thisWindowOpened(e);
			}
		});
		Container contentPane = getContentPane();

		//======== scrollPane1 ========
		{
			scrollPane1.setViewportView(tableProductAdd);
		}

		//---- btnProductAdd ----
		btnProductAdd.setText("Th\u00eam");
		btnProductAdd.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btnProductAddActionPerformed(e);
			}
		});

		//---- txtProductAddQuantity ----
		txtProductAddQuantity.setText("1");
		txtProductAddQuantity.addKeyListener(new KeyAdapter() {
			@Override
			public void keyTyped(KeyEvent e) {
				txtProductAddQuantityKeyTyped(e);
			}
		});

		//---- label1 ----
		label1.setText("S\u1ed1 l\u01b0\u01a1ng");

		//---- label2 ----
		label2.setText("Tu khoa");

		//---- btnProductAddSearch ----
		btnProductAddSearch.setText("Tim kiem");
		btnProductAddSearch.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btnProductAddSearchActionPerformed(e);
			}
		});

		//======== scrollPane2 ========
		{
			scrollPane2.setViewportView(tableOrderDetail);
		}

		//---- btnProductDelete ----
		btnProductDelete.setText("X\u00f3a s\u1ea3n ph\u1ea9m");
		btnProductDelete.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btnProductDeleteActionPerformed(e);
			}
		});

		//---- btnOrderDetailReload ----
		btnOrderDetailReload.setText("T\u1ea3i l\u1ea1i d\u1eef li\u1ec7u");
		btnOrderDetailReload.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btnOrderReloadActionPerformed(e);
				btnOrderDetailReloadActionPerformed(e);
			}
		});

		//---- btnOrderDetailSaveAll ----
		btnOrderDetailSaveAll.setText("L\u01b0u d\u1eef li\u1ec7u");
		btnOrderDetailSaveAll.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				btnOrderDetailSaveAllActionPerformed(e);
			}
		});

		GroupLayout contentPaneLayout = new GroupLayout(contentPane);
		contentPane.setLayout(contentPaneLayout);
		contentPaneLayout.setHorizontalGroup(
			contentPaneLayout.createParallelGroup()
				.addComponent(scrollPane1, GroupLayout.DEFAULT_SIZE, 659, Short.MAX_VALUE)
				.addGroup(contentPaneLayout.createSequentialGroup()
					.addContainerGap()
					.addGroup(contentPaneLayout.createParallelGroup()
						.addComponent(scrollPane2, GroupLayout.DEFAULT_SIZE, 639, Short.MAX_VALUE)
						.addGroup(contentPaneLayout.createSequentialGroup()
							.addComponent(label2, GroupLayout.PREFERRED_SIZE, 137, GroupLayout.PREFERRED_SIZE)
							.addGap(53, 53, 53)
							.addComponent(txtProductAddKeyword, GroupLayout.PREFERRED_SIZE, 195, GroupLayout.PREFERRED_SIZE)
							.addGap(29, 29, 29)
							.addComponent(btnProductAddSearch)
							.addGap(0, 152, Short.MAX_VALUE))
						.addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
							.addGap(0, 333, Short.MAX_VALUE)
							.addComponent(label1, GroupLayout.PREFERRED_SIZE, 117, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
							.addComponent(txtProductAddQuantity, GroupLayout.PREFERRED_SIZE, 102, GroupLayout.PREFERRED_SIZE)
							.addGap(18, 18, 18)
							.addComponent(btnProductAdd)))
					.addContainerGap())
				.addGroup(contentPaneLayout.createSequentialGroup()
					.addGap(166, 166, 166)
					.addComponent(btnProductDelete)
					.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
					.addComponent(btnOrderDetailReload)
					.addGap(6, 6, 6)
					.addComponent(btnOrderDetailSaveAll)
					.addGap(0, 198, Short.MAX_VALUE))
		);
		contentPaneLayout.setVerticalGroup(
			contentPaneLayout.createParallelGroup()
				.addGroup(GroupLayout.Alignment.TRAILING, contentPaneLayout.createSequentialGroup()
					.addContainerGap()
					.addComponent(scrollPane2, GroupLayout.PREFERRED_SIZE, 208, GroupLayout.PREFERRED_SIZE)
					.addGap(18, 18, 18)
					.addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.TRAILING)
						.addComponent(btnProductDelete)
						.addGroup(contentPaneLayout.createParallelGroup()
							.addComponent(btnOrderDetailReload)
							.addComponent(btnOrderDetailSaveAll)))
					.addGap(38, 38, 38)
					.addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
						.addComponent(label2)
						.addComponent(txtProductAddKeyword, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(btnProductAddSearch))
					.addGap(22, 22, 22)
					.addComponent(scrollPane1, GroupLayout.PREFERRED_SIZE, 167, GroupLayout.PREFERRED_SIZE)
					.addGap(18, 18, 18)
					.addGroup(contentPaneLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
						.addComponent(btnProductAdd)
						.addComponent(txtProductAddQuantity, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
						.addComponent(label1))
					.addContainerGap(153, Short.MAX_VALUE))
		);
		pack();
		setLocationRelativeTo(getOwner());
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	// Generated using JFormDesigner Evaluation license - Hoan Tran
	private JScrollPane scrollPane1;
	private JTable tableProductAdd;
	private JButton btnProductAdd;
	private JTextField txtProductAddQuantity;
	private JLabel label1;
	private JTextField txtProductAddKeyword;
	private JLabel label2;
	private JButton btnProductAddSearch;
	private JScrollPane scrollPane2;
	private JTable tableOrderDetail;
	private JButton btnProductDelete;
	private JButton btnOrderDetailReload;
	private JButton btnOrderDetailSaveAll;
	// JFormDesigner - End of variables declaration  //GEN-END:variables
}
